package com.tensequare.spit.service;

import com.tensequare.spit.dao.SpitDao;
import com.tensequare.spit.pojo.Spit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import common.util.IdWorker;

import java.util.List;

/**
 * @Author: Feng.Wang
 * @Company: Zelin.ShenZhen
 * @Description:
 * @Date: Create in 2019/3/25 16:08
 */
@Service
public class SpitService {
    @Autowired
    private SpitDao spitDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 查询列表
     * @return
     */
    public List<Spit> findAll(){
        return spitDao.findAll();
    }

    /**
     * 根据id查询
     * @param spitId
     * @return
     */
    public Spit findById(String spitId){
        return spitDao.findById(spitId).get();
    }

    /**
     * 添加吐槽
     * @param spit
     */
    public void add(Spit spit){
        spit.set_id(idWorker.nextId() + "");
        spitDao.save(spit);
    }

    /**
     *
     * @param spit
     */
    public void update(Spit spit){
        spitDao.save(spit);
    }

    /**
     * 根据吐槽id删除吐槽信息
     * @param spitId
     */
    public void deleteById(String spitId){
        spitDao.deleteById(spitId);
    }

    public Page<Spit> findByParentid(String parentid,int page,int size){
        return spitDao.findByParentid(parentid, PageRequest.of(page-1,size));
    }
    /**
     * 修改点赞(传统方法：性能不高)
     */
//    public void updateThumbup(String spitId){
//        //1.根据id取出吐槽对象
//        Spit spit = this.findById(spitId);
//        //2.修改点赞数
//        spit.setThumbup(spit.getThumbup() + 1);
//        //3.保存回去
//        spitDao.save(spit);
//    }

    /**
     * 将点赞数自增
     * @param spitId
     */
    public void updateThumbup(String spitId){
        //1.从redis中取出点赞成功放进去的变 量，如果有值证明点赞过
        Object obj = redisTemplate.opsForValue().get("thumbup_" + spitId);
        //2.如果取得的值不为空，就抛出异常
        if(obj != null){
            throw new RuntimeException("你己点赞了！");
        }else{
            //构造查询后的条件
            Query query = new Query();
            query.addCriteria(Criteria.where("_id").is(spitId));
            Update update = new Update();
            update.inc("thumbup",1);
            mongoTemplate.updateFirst(query,update,"spit");
            //在redis中存放一个标记的值（key："thumbup_" + spitId）
            redisTemplate.opsForValue().set("thumbup_" + spitId,"1");
        }
    }


}
